import sys
import keyboard
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow
from PyQt5 import QtCore, QtGui, QtWidgets

from PyQt5.QtCore import qAbs, QRect, Qt
from PyQt5.QtGui import QPen, QPainter, QColor, QGuiApplication
from PyQt5 import Qt as Qt1
from aip import AipOcr
import os
import re


class SteelWin(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self.init_ui()

    def init_ui(self):
        self.setFixedSize(150, 100)
        self.label = Qt1.QLabel('fdsfs', self)
        self.label.resize(150, 50)
        self.label.move(0, 0)
        self.label.setStyleSheet('background-color:green;color: white')
        self.label1 = Qt1.QLabel('', self)
        self.label1.resize(150, 50)
        self.label1.move(0, 50)
        self.label1.setStyleSheet('background-color:black')
        self.setWindowOpacity(0.85)  # 设置窗口透明度
        self.setAttribute(QtCore.Qt.WA_TranslucentBackground)  # 设置窗口背景透明
        # self.setWindowFlag(QtCore.Qt.FramelessWindowHint)  # 隐藏边框
        self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)  # 顶置
        # print("steel")


class CaptureScreen(QWidget):
    # 初始化变量
    beginPosition = None
    endPosition = None
    fullScreenImage = None
    captureImage = None
    isMousePressLeft = None
    painter = QPainter()
    img_s = []
    img_i = 0
    st_win = []
    client = None
    steel = [0, 0]

    def __init__(self):
        super(QWidget, self).__init__()
        self.initWindow()   # 初始化窗口
        self.captureFullScreen()    # 获取全屏
        self.client = ocr_aip_init()
        print(ocr_aip_2("pn.png", self.client)[0]["words"], "请按F4开始")

    def initWindow(self):
        self.setMouseTracking(True)     # 鼠标追踪
        self.setCursor(QtCore.Qt.CrossCursor)  # 设置光标
        self.setWindowFlag(QtCore.Qt.FramelessWindowHint)  # 窗口无边框
        self.setWindowState(QtCore.Qt.WindowFullScreen)    # 窗口全屏

    def captureFullScreen(self):
        self.fullScreenImage = QGuiApplication.primaryScreen(
        ).grabWindow(QApplication.desktop().winId())

    def labwith(self, i2):
        self.st_win[self.img_i].setFixedSize(len_c(i2) * 12 + 20, 100)
        self.st_win[self.img_i].label.resize(len_c(i2) * 12 + 20, 50)
        self.st_win[self.img_i].label1.resize(len_c(i2) * 12 + 20, 50)

    def mousePressEvent(self, event):

        if event.button() == QtCore.Qt.LeftButton:
            self.beginPosition = event.pos()
            self.endPosition = event.pos()
            self.isMousePressLeft = True
        if event.button() == QtCore.Qt.RightButton:
            # # 如果选取了图片,则按一次右键开始重新截图
            # if self.captureImage is not None:
            #     self.captureImage = None
            #     self.paintBackgroundImage()
            #     self.update()
            # else:
            #     self.close()
            print("鼠标右键")

            for i in range(len(self.st_win)):
                self.st_win[i].close()
            self.close()

    def mouseMoveEvent(self, event):
        if self.isMousePressLeft is True:
            self.endPosition = event.pos()

            self.update()

    def mouseReleaseEvent(self, event):
        self.endPosition = event.pos()
        self.isMousePressLeft = False
        if self.captureImage is not None:
            self.saveImage()
            # 生成识别的窗口
            self.st_win.append(SteelWin())
            print(self.img_i)

            # print(event.pos().x())
            self.st_win[self.img_i].move(
                self.beginPosition.x(), self.beginPosition.y() - 50)

            self.st_win[self.img_i].setWindowFlag(
                QtCore.Qt.FramelessWindowHint)
            self.st_win[self.img_i].show()

            res = ocr_aip_2('pn{0}.png'.format(self.img_i), self.client)
            if res:
                i0 = ""
                for i in res:
                    i0 = i['words'] + i0
                print(i0)
                i1 = evdata(i0)[0]
                if evdata(i0)[0] == evdata(i0)[1]:
                    i2 = i0
                else:
                    i2 = evdata(i0)[1] + "=" + evdata(i0)[0]
                    if evdata(i0)[0].isdigit:
                        if " " in evdata(i0)[0]:
                            tem = re.split(r"\s+", evdata(i0)[0])
                            temm = tem[0]
                        else:
                            temm = evdata(i0)[0]
                        self.steel[self.img_i] = float(temm)
                self.st_win[self.img_i].label.setText(i2)
                self.labwith(i2)
                self.st_win[self.img_i].setWindowFlag(
                    QtCore.Qt.FramelessWindowHint)
                self.st_win[self.img_i].show()
                if evdata(i0)[0].isdigit:
                    self.img_i = self.img_i + 1
                if self.img_i == 2:
                    print(self.steel[0], self.steel[1])
                    print("底筋/顶筋：", self.steel[0] / self.steel[1])
                    self.img_i = 0

    def mouseDoubleClickEvent(self, event):
        if self.captureImage is not None:
            self.saveImage()
            self.close()

    def keyPressEvent(self, event):
        print("esc")
        if event.key() == Qt.Key_Escape:
            for i in range(self.img_i):
                self.st_win[i].close()
            self.close()
        if event.key() == Qt.Key_Enter or event.key() == Qt.Key_Return:
            if self.captureImage is not None:
                self.saveImage()
                self.close()

    def paintBackgroundImage(self):
        shadowColor = QColor(0, 0, 0, 100)  # 黑色半透明
        self.painter.drawPixmap(0, 0, self.fullScreenImage)
        self.painter.fillRect(self.fullScreenImage.rect(),
                              shadowColor)     # 填充矩形阴影

    def paintEvent(self, event):
        self.painter.begin(self)    # 开始重绘
        self.paintBackgroundImage()
        penColor = QColor(30, 144, 245)     # 画笔颜色
        # 设置画笔,蓝色,1px大小,实线,圆形笔帽
        self.painter.setPen(
            QPen(penColor, 1, QtCore.Qt.SolidLine, QtCore.Qt.RoundCap))
        if self.isMousePressLeft is True:
            pickRect = self.getRectangle(
                self.beginPosition, self.endPosition)   # 获得要截图的矩形框
            self.captureImage = self.fullScreenImage.copy(
                pickRect)         # 捕获截图矩形框内的图片
            self.painter.drawPixmap(
                pickRect.topLeft(), self.captureImage)  # 填充截图的图片
            self.painter.drawRect(pickRect)     # 画矩形边框
        self.painter.end()  # 结束重绘

    def getRectangle(self, beginPoint, endPoint):
        pickRectWidth = int(qAbs(beginPoint.x() - endPoint.x()))
        pickRectHeight = int(qAbs(beginPoint.y() - endPoint.y()))
        pickRectTop = beginPoint.x() if beginPoint.x() < endPoint.x() else endPoint.x()
        pickRectLeft = beginPoint.y() if beginPoint.y() < endPoint.y() else endPoint.y()
        pickRect = QRect(pickRectTop, pickRectLeft,
                         pickRectWidth, pickRectHeight)
        # 避免高度宽度为0时候报错
        if pickRectWidth == 0:
            pickRect.setWidth(2)
        if pickRectHeight == 0:
            pickRect.setHeight(2)

        return pickRect

    def saveImage(self):
        self.captureImage.save('pn{0}.png'.format(self.img_i), quality=95)

        # 保存图片到当前文件夹中


# ocr 识别模块 下面两个是分布模块，第三个函数是完整模块，分开会对多次ocr有加速作用
def ocr_aip_init():
    APP_ID = '25827715'
    API_KEY = '8rb7DAjL6wYFUMwMyjKRcV2r'
    SECRET_KEY = 'MCIQsXlt0lgF4bHnonRKIehfdwsTb7V4'
    client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
    return client


def ocr_aip_2(img_path, client):
    def get_file_content(filePath):
        with open(filePath, "rb") as fp:
            return fp.read()
    img_p = get_file_content(img_path)
    res_y = client.basicAccurate(img_p)
    if "words_result" in res_y.keys():
        return res_y['words_result']
    # ocr 有basicGeneral basicAccurate general accurate等等
    return None


def ocr_aip(img_path):
    APP_ID = '25827715'
    API_KEY = '8rb7DAjL6wYFUMwMyjKRcV2r'
    SECRET_KEY = 'MCIQsXlt0lgF4bHnonRKIehfdwsTb7V4'
    client = AipOcr(APP_ID, API_KEY, SECRET_KEY)

    def get_file_content(filePath):
        with open(filePath, "rb") as fp:
            return fp.read()
    img_p = get_file_content(img_path)

    # ocr 有basicGeneral basicAccurate general accurate等等
    return client.basicAccurate(img_p)['words_result']


def evdata(strs):

    def st_0(ma):
        return ma.group() + " "

    def st(ma):
        s1 = ma.group(1)
        s2 = ma.group(2)

        return str(int(eval(s1 + "*" + "3.14*((" + s2 + "/2)**2)"))) + " "

    def sa_0(ma):
        if len(ma.group()) == 3:
            s1 = ma.group()[0]
            s2 = ma.group()[1:]

        elif len(ma.group()) == 4:
            if int(ma.group()[2]) > 3 or int(ma.group()[0]) > 2:
                s1 = ma.group()[0]
                s2 = ma.group()[1:3]
            else:
                s1 = ma.group()[0:2]
                s2 = ma.group()[2:]
        elif len(ma.group()) > 4:
            s1 = ma.group()[0]
            s2 = ma.group()[1:3]
        else:
            return ma.group()

        # print(s1, s2)
        return s1 + "c" + s2 + " "

    def sadd(ma):
        s1 = ma.group(1)
        s2 = ma.group(2)
        return str(eval(s1 + "+" + s2))

    strs = re.sub("[业亚世企]", "c", strs)
    rstrs_0 = strs
    # print(strs)

    rstrs_0 = re.sub(r"(\d{1,2}c\d\d)", st_0, rstrs_0)
    # print(rstrs_0)
    rstrs_0 = re.sub(r"\d+", sa_0, rstrs_0)
    # print(rstrs_0)
    # 去掉空格
    rstrs_0 = re.sub(r"\s+", "", rstrs_0)
    # print(rstrs_0)
    if re.search(r"(\d{1,2}c\d\d)(\+\dc\d\d)?(/\dc\d\d)?(\+\dc\d\d)?", rstrs_0):
        rstrs_0 = re.search(
            r"(\d{1,2}c\d\d)(\+\dc\d\d)?(/\dc\d\d)?(\+\dc\d\d)?", rstrs_0).group()
        # print(rstrs_0)
        rstrs = re.sub(r"(\d+)c(\d{1,2})", st, rstrs_0)

       # 有加法的处理一下
        if "+" in rstrs:
            rstrs = re.sub(r"\s+", "", rstrs, 1)
            rstrs = re.sub(r"(\d+)\+(\d+)", sadd, rstrs)
        # print(rstrs, rstrs_0)
        if "/" in rstrs:
            ss = re.split("/", rstrs)
            # print(ss[0], ss[1])
            if len(ss[0]) > 2 and len(ss[1]) > 2 and ss[0].isdigit and ss[1].isdigit:
                rstrs = str(eval(re.sub(r"\s+", "", ss[0] + "+" + ss[1])))
    else:
        return rstrs_0, rstrs_0

    return rstrs, rstrs_0


# 考虑汉字比数字宽增设的函数


def len_c(strs):
    i_c = 0
    for i in strs:
        if ord(i) - ord("0") >= 128:
            i_c += 1
    return i_c + len(strs)


if __name__ == "__main__":
    keyboard.wait(hotkey='f4')  # 按F4开始截图
    app = QApplication(sys.argv)
    windows = CaptureScreen()
    windows.show()
    sys.exit(app.exec_())
    print("df")
